package facade;

import java.util.List;
import java.util.Vector;

import org.yaz4j.Connection;
import org.yaz4j.PrefixQuery;
import org.yaz4j.ResultSet;

import dao.ResourceDAO;
import dao.UserDAO;
import domain.Query;
import domain.Resource;
import domain.User;
import domain.util.ParserGenerated;

public class Facade {

	private ResourceDAO resourceDao = new ResourceDAO();
	private UserDAO userDao = new UserDAO();

	private static Facade facadeInstance = new Facade();

	protected Facade() {

	}

	public static Facade getInstance() {
		return facadeInstance;
	}

	// =============================Resource DAO=================================

	public boolean addResource(Resource resource) {
		return resourceDao.save(resource);
	}
	
	public boolean createResource(Resource resource) {
		return resourceDao.save(resource);
	}
	public List getResourcesBy(String key, String value) {
		return resourceDao.getResourcesBy(key,value);
	}
	public Resource getResourcesById(long id) {
		return resourceDao.getResourcesById(id);
	}
	

	// =============================User DAO=================================
	public User getUser(String login) {
		return userDao.getUser(login);
	}

	// =============================Z3950 Search=============================
	public List<String> search (Query q, int offset, int count) {
		Connection conn = new Connection("z3950.loc.gov", 7090);
		conn.setDatabaseName("Voyager");
		conn.setSyntax("USMARC");

		String search = "@attr 1=" + q.getMode() + " \"" + q.getQuery() + "\"";
		System.out.println(search);
		PrefixQuery query = new PrefixQuery(search);
		ResultSet rs = conn.Search(query);
		
		 List<String> result = new Vector<String>(count);
		for (int i = 0; i < Math.min(count, rs.getSize() - offset); i++) {
			result.add(rs.getRecord(i + offset).render());
		}
		
		conn.Dispose();
		return result;
	}
	
	public String search(Query q, int index) {
		Connection conn = new Connection("z3950.loc.gov", 7090);
		conn.setDatabaseName("Voyager");
		conn.setSyntax("USMARC");

		String search = "@attr 1=" + q.getMode() + " \"" + q.getQuery() + "\"";
		System.out.println(search);
		PrefixQuery query = new PrefixQuery(search);
		ResultSet rs = conn.Search(query);
		
		return rs.getRecord(index).render();
	}
	
	public int search(Query q) {
		Connection conn = new Connection("z3950.loc.gov", 7090);
		conn.setDatabaseName("Voyager");
		conn.setSyntax("USMARC");

		String search = "@attr 1=" + q.getMode() + " \"" + q.getQuery() + "\"";
		PrefixQuery query = new PrefixQuery(search);
		ResultSet rs = conn.Search(query);
		
		conn.Dispose();
		return rs.getSize();
	}
	
	public Resource download(Query q, int index) {
		return ParserGenerated.getResourceFromMarc(Facade.getInstance().search(q, index));
	}
}
